package com.campus.help.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.common.PageResult;
import com.campus.help.common.Result;
import com.campus.help.dto.SecondHandProductDTO;
import com.campus.help.dto.SecondHandProductInputDTO;
import com.campus.help.entity.Secondhand;
import com.campus.help.mapper.SecondhandMapper;
import com.campus.help.mapper.SecondhandTypeMapper;
import com.campus.help.vo.SecondhandVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 二手商品管理控制器
 *
 * @author campus-help
 * @since 2025-10-17
 */
@Slf4j
@RestController
@RequestMapping("/admin/second-hand-products")
public class AdminSecondHandController {

    @Autowired
    private SecondhandMapper secondhandMapper;

    @Autowired
    private SecondhandTypeMapper secondhandTypeMapper;

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("二手商品管理接口正常工作");
    }

    /**
     * 分页查询二手商品列表
     */
    @GetMapping
    public Result<PageResult<SecondHandProductDTO>> getProductPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String status) {
        
        try {
            log.info("查询二手商品列表，页码：{}，每页大小：{}，关键词：{}，类别：{}，状态：{}", 
                    page, size, keyword, categoryId, status);
            
            // 创建分页对象
            Page<SecondhandVO> pageObj = new Page<>(page, size);
            
            // 使用mapper方法查询（包含类型和卖家信息）
            // 管理员可以查看所有学校的商品，所以schoolId传null
            Page<SecondhandVO> result = secondhandMapper.selectSecondhandListWithInfo(
                pageObj, 
                keyword,     // 关键词
                categoryId,  // 类别ID
                null,        // 地点
                null,        // 最低价格
                null,        // 最高价格
                null,        // 成色
                status,      // 状态
                null         // schoolId - 管理员查看所有学校
            );
            
            // 转换为DTO
            List<SecondHandProductDTO> dtoList = result.getRecords().stream()
                    .map(SecondHandProductDTO::fromVO)
                    .collect(Collectors.toList());
            
            PageResult<SecondHandProductDTO> pageResult = new PageResult<>(
                result.getCurrent(),
                result.getSize(),
                result.getTotal(),
                dtoList
            );
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询二手商品列表失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询商品详情
     */
    @GetMapping("/{id}")
    public Result<SecondhandVO> getProductById(@PathVariable Long id) {
        try {
            log.info("查询二手商品详情，ID：{}", id);
            
            SecondhandVO product = secondhandMapper.selectSecondhandDetailById(id);
            if (product == null) {
                return Result.error("商品不存在");
            }
            
            return Result.success(product);
        } catch (Exception e) {
            log.error("查询二手商品详情失败，ID：{}", id, e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 添加二手商品
     */
    @PostMapping
    public Result<String> addProduct(@RequestBody SecondHandProductInputDTO productDTO) {
        try {
            log.info("添加二手商品，商品名称：{}", productDTO.getProductName());
            
            // 参数校验
            if (productDTO.getProductName() == null || productDTO.getProductName().trim().isEmpty()) {
                return Result.error("商品名称不能为空");
            }
            
            if (productDTO.getDescription() == null || productDTO.getDescription().trim().isEmpty()) {
                return Result.error("商品描述不能为空");
            }
            
            if (productDTO.getCategoryId() == null) {
                return Result.error("商品类别不能为空");
            }
            
            if (productDTO.getPrice() == null || productDTO.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("商品价格必须大于0");
            }
            
            // 转换为实体
            Secondhand product = productDTO.toEntity();
            
            // 设置默认值
            if (product.getStatus() == null || product.getStatus().trim().isEmpty()) {
                product.setStatus("on_sale");
            }
            
            if (product.getViewCount() == null) {
                product.setViewCount(0);
            }
            
            if (product.getFavoriteCount() == null) {
                product.setFavoriteCount(0);
            }
            
            if (product.getIsUrgent() == null) {
                product.setIsUrgent(0);
            }
            
            if (product.getFreeShipping() == null) {
                product.setFreeShipping(0);
            }
            
            if (product.getNegotiable() == null) {
                product.setNegotiable(0);
            }
            
            // 插入数据
            int result = secondhandMapper.insert(product);
            if (result > 0) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加二手商品失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新二手商品
     */
    @PutMapping("/{id}")
    public Result<String> updateProduct(@PathVariable Long id, @RequestBody SecondHandProductInputDTO productDTO) {
        try {
            log.info("更新二手商品，ID：{}，商品名称：{}", id, productDTO.getProductName());
            
            // 检查是否存在
            Secondhand existing = secondhandMapper.selectById(id);
            if (existing == null || existing.getDeleted() == 1) {
                return Result.error("商品不存在");
            }
            
            // 参数校验
            if (productDTO.getProductName() == null || productDTO.getProductName().trim().isEmpty()) {
                return Result.error("商品名称不能为空");
            }
            
            if (productDTO.getDescription() == null || productDTO.getDescription().trim().isEmpty()) {
                return Result.error("商品描述不能为空");
            }
            
            if (productDTO.getCategoryId() == null) {
                return Result.error("商品类别不能为空");
            }
            
            if (productDTO.getPrice() == null || productDTO.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("商品价格必须大于0");
            }
            
            // 转换为实体
            Secondhand product = productDTO.toEntity();
            
            // 设置ID并更新
            product.setId(id);
            int result = secondhandMapper.updateById(product);
            
            if (result > 0) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新二手商品失败，ID：{}", id, e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除二手商品（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteProduct(@PathVariable Long id) {
        try {
            log.info("删除二手商品，ID：{}", id);
            
            // 检查是否存在
            Secondhand product = secondhandMapper.selectById(id);
            if (product == null || product.getDeleted() == 1) {
                return Result.error("商品不存在");
            }
            
            // 逻辑删除
            product.setDeleted(1);
            int result = secondhandMapper.updateById(product);
            
            if (result > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除二手商品失败，ID：{}", id, e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 更新商品状态
     */
    @PutMapping("/{id}/status")
    public Result<String> updateStatus(@PathVariable Long id, @RequestBody Map<String, String> requestBody) {
        try {
            String status = requestBody.get("status");
            log.info("更新二手商品状态，ID：{}，状态：{}", id, status);
            
            // 检查是否存在
            Secondhand product = secondhandMapper.selectById(id);
            if (product == null || product.getDeleted() == 1) {
                return Result.error("商品不存在");
            }
            
            // 状态校验
            if (status == null || status.trim().isEmpty()) {
                return Result.error("状态值不能为空");
            }
            
            if (!status.equals("on_sale") && !status.equals("sold") && !status.equals("off_shelf")) {
                return Result.error("状态值无效");
            }
            
            // 更新状态
            product.setStatus(status);
            int result = secondhandMapper.updateById(product);
            
            if (result > 0) {
                String statusText = "";
                switch (status) {
                    case "on_sale":
                        statusText = "上架";
                        break;
                    case "sold":
                        statusText = "标记为已售";
                        break;
                    case "off_shelf":
                        statusText = "下架";
                        break;
                }
                return Result.success(statusText + "成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("更新二手商品状态失败，ID：{}", id, e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除商品
     */
    @DeleteMapping("/batch")
    public Result<String> batchDelete(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            java.util.List<Long> ids = (java.util.List<Long>) params.get("ids");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的商品");
            }
            
            log.info("批量删除二手商品，数量：{}", ids.size());
            
            int count = 0;
            for (Long id : ids) {
                Secondhand product = secondhandMapper.selectById(id);
                if (product != null && product.getDeleted() == 0) {
                    product.setDeleted(1);
                    secondhandMapper.updateById(product);
                    count++;
                }
            }
            
            return Result.success("成功删除" + count + "个商品");
        } catch (Exception e) {
            log.error("批量删除二手商品失败", e);
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }
}

